import { Button, Collapse, Card } from 'antd'
import { SelfCheckBoard, GpioCard, RS422Card } from '@/components'
import { useMemo, useState } from 'react'
import { GPIOTest, RS422Test } from '@/api/common.api'

interface IOItem {
  id: number
  name: string
  defaultValue: number
  reaction?: string
  type: string
}

interface Props {
  computerId: number
  cpuName: string
  cpuId: number,
  link: {
    port: number,
    host: string
  },
  GPIO: IOItem[]
  RS422: IOItem[]
}


export function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time)
  })
}



export default function CpuTabPane(
  props: Props = { GPIO: [], RS422: [], computerId: 0, cpuName: 'RISCV', cpuId: 0 }
) {
  const { GPIO, RS422, computerId, cpuName, cpuId, link } = props

  const [GPIOList, setGPIOList] = useState([...GPIO])
  const [RS422List, setRS422List] = useState([...RS422])

  const handleClick = async ({ id }) => {

    const state = GPIOList.find((item) => item.id === id)
    const result = await GPIOTest({
      number: state?.id,
      state: state?.defaultValue,
      cpuId: cpuId,
      computerId: computerId,
      link,
      type: state.type
    })
    const list = GPIOList.map((item) => {
      if (item.id === result.number) {
        return {
          ...item,
          value: result.value,
          reaction: result.reaction
        }
      }
      return item
    })
    setGPIOList(list)
    console.log('handleClick', result)
  }

  const handleChange = (event, state) => {
    const list = GPIOList.map((item) => {
      if (item.id === state.id) {
        return {
          ...item,
          defaultValue: event.target.value
        }
      }
      return item
    })

    setGPIOList(list)
  }

  const handleSetAll = (value: 0 | 1) => {
    const list = GPIOList.map((item) => {
      return {
        ...item,
        defaultValue: value
      }
    })
    setGPIOList(list)
  }




  async function runSerial(tasks) {
    const results = [];
    for (let i = 0; i < tasks.length; i++) {
      const task = tasks[i];
      const res = await task();
      results.push(res);

    }

    return results;
  }

  const handleBatchTest = async () => {
    const testList = GPIOList.map((item) => {
      return async () => {
        await sleep(600)
        return await GPIOTest({
          number: item.id,
          state: item.defaultValue,
          cpuId: cpuId,
          computerId: computerId,
          link,
          type: item.type
        })
      }
    })
    runSerial(testList).then(results => {
      const list = results.map((res) => {
        const state = GPIOList.find((item) => item.id === res.number)
        return {
          ...state,
          value: res.value,
          reaction: res.reaction
        }
      })
      console.log(list)
      setGPIOList(list)
    });




  }

  const handleRS422Click = async ({ id }) => {
    const state = RS422List.find((item) => item.id === id)
    const result = await RS422Test({ number: state?.id, state: state?.defaultValue, connect: state.connect })
    const list = RS422List.map((item) => {
      if (item.id === result.number) {
        return {
          ...item,
          value: result.value,
          reaction: result.reaction
        }
      }
      return item
    })
    setRS422List(list)
    console.log('handleClick', result)
  }



  const handleRS422BatchTest = async () => {

    const testList = RS422List.map(async (item) => {
      return async () => {
        await sleep(20)
        return await RS422Test({ number: item.id, state: item.defaultValue, connect: state.connect  })
      }
    })

    runSerial(testList).then(results => {

      const list = results.map((res) => {
        const state = RS422List.find((item) => item.id === res.number)
        return {
          ...state,
          value: res.value,
          reaction: res.reaction
        }
      })
      setRS422List(list)


    });






  }

  return (
    <>

      <SelfCheckBoard computerId={computerId} cpuName={cpuName} cpuId={cpuId} link={link} className="mb-2" />
      <Card
        title="GPIO"
        extra={
          <div className="flex gap-2">
            <Button
              size="small"
              onClick={(e) => {
                e.stopPropagation()
                handleSetAll(0)
              }}
            >
              全选0
            </Button>
            <Button
              size="small"
              onClick={(e) => {
                e.stopPropagation()
                handleSetAll(1)
              }}
            >
              全选1
            </Button>
            <Button
              type="primary"
              size="small"
              onClick={(e) => {
                e.stopPropagation()
                handleBatchTest()
              }}
            >
              批量测试
            </Button>
          </div>
        }
      >
        <div className="grid grid-cols-4 gap-4">
          {GPIOList.map((item, index) => (
            <GpioCard
              key={`GPIO-${index}`}
              {...item}
              onChange={(event) => handleChange(event, item)}
              onClick={() => handleClick(item)}
            />
          ))}
        </div>
      </Card>

      <Card
        title="RS422"
        // extra={
        //   <Button
        //     type="primary"
        //     size="small"
        //     onClick={(e) => {
        //       e.stopPropagation()
        //       handleRS422BatchTest()
        //     }}
        //   >
        //     批量测试
        //   </Button>
        // }
      >
        <div className="grid grid-cols-4 gap-4">
          {RS422List.map((item, index) => (
            <RS422Card
              key={`RS422-${index}`}
              {...item}

              onClick={() => handleRS422Click(item)}
            />
          ))}
        </div>
      </Card>

      {/* <Collapse
        defaultActiveKey={['GPIO', 'RS422']}
        expandIconPosition="start"
        items={data.map(({ name, list }) => {
          return {
            key: name,
            label: name,
            extra: (
              <div onClick={(e) => e.stopPropagation()} className="flex gap-2">
                {name === 'GPIO' && (
                  <>
                    <Button
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation()
                        handleSetAll(list, 0)
                      }}
                    >
                      全选0
                    </Button>
                    <Button
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation()
                        handleSetAll(list, 1)
                      }}
                    >
                      全选1
                    </Button>
                  </>
                )}
                <Button
                  type="primary"
                  size="small"
                  onClick={(e) => {
                    e.stopPropagation()
                    handleBatchTest(name, list)
                  }}
                >
                  批量测试
                </Button>
              </div>
            ),
            children: (
              <div className="grid grid-cols-4 gap-4">
                {list.map((item, index) => (
                  <GpioCard
                    key={`gpiocard-${index}`}
                    cpuName={name}
                    data={item}
                    testValue={gpioState[item?.id].value}
                    testResult={gpioState[item?.id].result}
                    onValueChange={handleValueChange}
                    onTest={handleTest}
                  />
                ))}
              </div>
            )
          }
        })}
      /> */}
    </>
  )
}
